from flask import Blueprint, session, make_response, request, jsonify
from app.utils.captcha.captcha import Captcha
from app.utils.code import RET
from app.models import UserModel
import random
import os

api_captcha = Blueprint("api_captcha", __name__)

''' 获取图片验证码 '''
@api_captcha.route("/captcha/<uuid>")
def captcha(uuid):
    path = os.path.dirname(__file__)
    print(path)
    captcha_obj = Captcha(width=120, height=30, is_blur=False, font=path + "/../utils/captcha/Arial.ttf")
    image_data = captcha_obj.save_bytes_io()
    resp = make_response(image_data.getvalue())
    session['captcha_code_' + uuid] = "".join(captcha_obj.code)
    print(session['captcha_code_' + uuid])
    resp.headers["Content-Type"] = "image/jpg"
    return resp

''' 获取手机号验证码 '''
@api_captcha.route("/sendsms/<re(r'1[34578]\d{9}'):mobile>")
def sendsms(mobile):
    code = request.args.get("code", "")
    codeId = request.args.get("codeId", "")

    # 判断参数是否正确
    if not all([code, codeId]):
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")
    
    real_image_code = str(session['captcha_code_' + codeId]).lower()
    print("real_image_code=" + real_image_code)
    print("code="+code.lower())
    # 判断验证码是否正确
    if code.lower() != real_image_code:
        return jsonify(errno = RET.PARAMERR, errmsg = "验证码不正确")
    
    # 判断手机号是否存在
    user = UserModel.query.filter_by(mobile=mobile).first()
    if user is not None:
        return jsonify(errno = RET.DATAEXIST, errmsg = "手机号已经存在")

    # 如果手机号不存在，则生成短信验证码
    sms_code = "%06d" % random.randint(0, 999999)
    print("sms_code=" + sms_code)
    session['sms_code_' + mobile] = sms_code

    return jsonify(errno=RET.OK, errmsg="发送成功")